from django.shortcuts import render
from django.http import HttpResponse
from django.conf import settings
from django.core.cache import caches,cache
import csv
import time
from fundinfo.fundmodel import *
from analysis.basic_data import *

def getFundTypesInfo(fundList, totalCost):
    types = []
    for item in fundList:
        canAdd = True
        for type in types:
            if type[0] == item.type:
                canAdd = False
                type[1] = type[1] + item.cost
                type[2] = type[2] + item.incomeTotal
                break
        if canAdd:
            types.append([item.type, item.cost, item.incomeTotal, 0.0])

    # 刷新小数点和百分比
    for item in types:
        item[1] = round(item[1], 2)
        item[2] = round(item[2], 2)
        item[3] = round(item[2] * 100 / item[1], 2)
    return types

def getFundRiskInfo(fundList, totalCost):
    risks = []
    for item in fundList:
        canAdd = True
        for risk in risks:
            if risk[0] == item.risk:
                canAdd = False
                risk[1] = risk[1] + item.cost
                risk[2] = risk[2] + item.incomeTotal
                break
        if canAdd:
            risks.append([item.risk, round(item.cost, 2), round(item.incomeTotal, 2), 0.0])

    # 刷新小数点和百分比
    for item in risks:
        item[1] = round(item[1], 2)
        item[2] = round(item[2], 2)
        if item[1] != 0:
            item[3] = round(item[2] * 100 / item[1], 2)
    return risks

def getFundCostByTypeOrder(types, fundList):
    costs = []
    for type in types:
        for fund in fundList:
            if type[0] == fund.type and fund.cost != 0.0:
                costs.append([fund.name, round(fund.cost, 2)])
    return costs

def getFundName(code, fundList):
    for item in fundList:
        if item[0] == code:
            return item[1]
    return ""

# def getWarning(fundList):
#     info = ""
#     path = settings.ANALYSIS_DIR + "/monitor_rate.csv"
#     csvReader = None
#     try:
#         csvReader = csv.reader(open(path, encoding='utf-8'))
#     except:
#         return None
#     for item in csvReader:
#         if item[3] == 'True':
#             info = info + getFundName(item[0], fundList) + " " + item[1] + " " + item[2] + "days;"
#     return info

def fundListOrderKey(fundList):
    return float(fundList[7])

# def getMonthInome():
#     income = []
#     path = settings.ANALYSIS_DIR + "/month_income.csv"
#     csvReader = None
#     try:
#         csvReader = csv.reader(open(path, encoding='utf-8'))
#     except:
#         return None

#     for item in csvReader:
#         income.append([item[0], float(item[1])])
#     return income

def fundsOrderKey(a):
    return a.incomeRate


def filterZeroCost(lst):
    lst2 = []
    if lst == None:
        return lst2
    for item in lst:
        if item.cost == 0:
            continue
        lst2.append(item)
    return lst2

def getIndex(request):
    fundLst = BasicData.getTradingFundLst()
    fundLst = filterZeroCost(fundLst)
    info = {}
    fundLst.sort(key=lambda x: (x.incomeRate), reverse=True)

    # 基金数据
    info['funds'] = fundLst

    # 基金数量
    info['fundNum'] = len(info['funds'])

    # 总数据：成本，累计收益，持有收益，收益率
    cost = 0.0
    incomeTotal = 0.0
    income = 0.0

    for fund in fundLst:
        cost = cost + fund.cost # 累计成本
        incomeTotal = incomeTotal + fund.incomeTotal # 累计收益
        income = income + fund.income # 持有收益

    # 累计成本
    info['cost'] = round(cost)
    if info['cost'] == 0:
        info['cost'] = 1

    # 累计收益
    info['incomeTotal'] = round(incomeTotal)
    info['incomeTotalPercent'] = round(info['incomeTotal'] * 100 / info['cost'], 2)

    # 持有收益
    info['income'] = round(income)
    info['incomePercent'] = round(info['income'] * 100 / info['cost'], 2)

    info['types'] = getFundTypesInfo(fundLst, info['cost'])
    info['risks'] = getFundRiskInfo(fundLst, info['cost'])
    info['typeItems'] = getFundCostByTypeOrder(info['types'], fundLst)

    # info['warning'] = getWarning(fundList)

    info['monthIncome'] = BasicData.getTotalIncomMonthList()

    info['lastYearIncome'] = 0.0
    cnt = len(info['monthIncome'])
    for i in range(cnt- 12, cnt):
        if i < 0:
            continue
        info['lastYearIncome'] = info['lastYearIncome'] + info['monthIncome'][i].income
    info['lastYearIncome'] = round(info['lastYearIncome'])

    info['last2YearIncome'] = 0.0
    for i in range(cnt- 24, cnt):
        if i < 0:
            continue
        info['last2YearIncome'] = info['last2YearIncome'] + info['monthIncome'][i].income
    info['last2YearIncome'] = round(info['last2YearIncome'])

    #import akshare as ak
    #cnt = 0
    # fund_rating_all_df = ak.fund_rating_all()
    # for indx,data in fund_rating_all_df.iterrows():
    #     if data['5星评级家数'] >= 1:
    #         #print(data['代码'], data['简称'], data['5星评级家数'])
    #         try:
    #             fund_individual_basic_info_xq_df = ak.fund_individual_basic_info_xq(symbol=data['代码'])
    #             if fund_individual_basic_info_xq_df['基金评级'] == '五星基金':
    #                 print(fund_individual_basic_info_xq_df)
    #                 cnt = cnt + 1
    #         except:
    #             pass
            
    #         #break
    # print(cnt)

    return render(request,"index.html", info)
